const app = getApp()

Page({
    data: {
        xPageReady : true ,
        user: [
            { cn: '头像', key: 'avatarUrl', value: 'https://7633-v3-92ah4-1300208657.tcb.qcloud.la/static/avatarUrl.png', type: 'avatar' },
            { cn: '昵称', key: 'nickName', value: '', type: 'nickName' },
            { cn: '真实姓名', key: 'real_name', value: '', type: 'text' }, // 真实姓名
            { cn: '出生日期', key: 'birthday', value: '', type: 'date' }, // 出生日期
            { cn: '联系号码', key: 'phone_number', value: '', type: 'phone' }, // 联系方式
            { cn: '性别', key: 'sex', value: '', type: 'picker', range: ["男", "女"] }, // 性别
            { cn: '工作', key: 'work', value: '', type: 'picker', range: ["就业中", "待业中", "失业中", "创业中"], }, // 工作
            { cn: '婚恋状态', key: 'marriage_love_state', value: '', type: 'picker', range: ["单身", "已婚", "离婚", "丧偶", "恋爱中"] }, // 婚恋状态
            { cn: '所在地', key: 'city', value: '', type: 'address' }, // 所在地
            { cn: '子女数', key: 'all_child', value: '', type: 'picker', range: ["无子女", "1个", "2个", "3个及以上"] }, // 子女数
            { cn: '受教育程度', key: 'education', value: '', type: 'picker', range: ["小学", "初中", "高中", "中专", "大专", "本科", "硕士", "博士"] }, // 
        ],
        first:1,
        check1:false,
        check2:false,
        check3:false,
        check4:false,
        isUpdate:false,
        needSetting:app.globalData.needAuthorization
    },
    onLoad: function (options) {
        this.xInit()
    },
    xChildReload: function () {
      var pages = getCurrentPages();//当前页面栈
      if (pages.length > 1) {
        var beforePage = pages[pages.length - 2];//获取上一个页面实例对象
        beforePage.xInfo();//触发父页面中的方法
      }
    },
    handleAgreePrivacyAuthorization:function(){
      let privacyResolves = new Set()
      privacyResolves.forEach(resolve => {
        resolve({
          event: 'agree',
          buttonId: 'agree-btn'
        })
      })
    },
    onChooseAvatar(e) {
      let that = this
      const { avatarUrl } = e.detail 
      wx.cloud.uploadFile({
        cloudPath: 'profile/'  + new Date().getTime() + '.png',
        filePath: avatarUrl
      }).then( xRes => {
          console.log(xRes)
          wx.cloud.getTempFileURL({
              fileList: [xRes.fileID],
              success: xEnd => {
                let path = xEnd.fileList[0].tempFileURL
                that.setData({
                  [`user[0].value`]:path,
                  isUpdate:true
                })
              }
          })
      })
    },
    xInit: async function () {
        let that = this
        let user = that.data.user
        await wx.cloud.callFunction({
            name: "user",
            data: {
                action: "detail"
            }
        }).then(res => {
            let data = res.result
            for(var i in data){
                for(var j in user){
                  if(user[j].key === i){
                    user[j].value = data[i]
                  }
                }
            }
            for(let index in res.result.drugs_being_taken){
              if(res.result.drugs_being_taken[index]=='非甾体类(如阿司匹林、布洛芬、塞来西布等)'){
                that.setData({
                  check1:true
                })
              }
              if(res.result.drugs_being_taken[index]=='阿片类(如芬太尼、曲马多、吗啡等)'){
                that.setData({
                  check2:true
                })
              }
              if(res.result.drugs_being_taken[index]=='抗惊厥类(如安定、加巴喷丁、普瑞巴林等)'){
                that.setData({
                  check3:true
                })
              }
              if(res.result.drugs_being_taken[index]=='抗抑郁类(如阿米替林、度洛西汀、文拉法辛等)'){
                that.setData({
                  check4:true
                })
              }
            }

            that.setData({
                user : user
            })

            
        })

        that.setData({
            xPageReady : false
        })
    },
    checkboxChange(e) {
      let that = this
      let value = e.detail.value
      let params = e.currentTarget.dataset
      that.setData({
          [`user[${params.idx}].value`]: value
      })
    },
    xregion:function(e){
      let that = this
      let value =' '
      if(e.detail.value[0] !==  e.detail.value[1]){
        value  = e.detail.value[0]+ e.detail.value[1] 
      }else{
        value = e.detail.value[0]
      }
      let params = e.currentTarget.dataset
      that.setData({
          [`user[${params.idx}].value`]: value
      })
    },
    sliderchange:function(e){
      let that = this
      let value = e.detail.value
      let params = e.currentTarget.dataset
      that.setData({
          [`user[${params.idx}].value`]: value
      })
    },
    xInput: function (e) {
        let that = this
        let value = e.detail.value
        let params = e.currentTarget.dataset
        that.setData({
            [`user[${params.idx}].value`]: value
        })
      
    },
    bindblur(e){
      // let that = this
      // let value = e.detail.value
      // let params = e.currentTarget.dataset
      // that.setData({
      //     [`user[${params.idx}].value`]: value
      // })
    },
    bindnicknamereview:function(e){
      
    },
    nickChange:function(e){
      let that = this
      let value = e.detail.value
      let params = e.currentTarget.dataset
      that.setData({
          [`user[${params.idx}].value`]: value
      })
    },
    choose:function(e){
      let that = this
      let params = e.currentTarget.dataset
      that.setData({
          [`user[${params.idx}].value`]: params.value
      })
    },

    xPicker: function (e) {
        let that = this
        let sel = e.detail.value
        let params = e.currentTarget.dataset
        let range = that.data.user[params.idx].range
        let value = range[sel]
        that.setData({
            [`user[${params.idx}].value`]: value
        })
    },

    xDate: function (e) {
        let that = this
        let value = e.detail.value
        let params = e.currentTarget.dataset
        that.setData({
            [`user[${params.idx}].value`]: value
        })
    },
    handleTouchInput:function(){
      this.setData({
        innerShow:true
      })
    },
    changePrivacySetting:function(e){
      this.setData({
        needSetting:false
      })
    },
    xPhone: async function (e) {
        let that = this
        let params = e.currentTarget.dataset
        wx.showLoading({
            title: '请稍等',
        })
        await wx.cloud.callFunction({
            name: 'user',
            data: {
                action: 'getPhone',
                cloudID: e.detail.cloudID
            },
            success: function (res) {
              that.setData({
                  [`user[${params.idx}].value`]: res.result.phoneNumber
              })
            }
        })
        wx.hideLoading()
    },

    xLocation: async function (e) {
        let that = this
        let params = e.currentTarget.dataset

        // wx.showLoading({
        //     title: '请稍等',
        // })

        // await wx.getLocation({
        //     type: 'wgs84',
        //     success(res) {
        //         const latitude = res.latitude
        //         const longitude = res.longitude
        //         const speed = res.speed
        //         const accuracy = res.accuracy
        //         wx.request({
        //             url: `https://apis.map.qq.com/ws/geocoder/v1/?key=CQ3BZ-OXQKP-7RLDJ-L4FP5-VLIIH-ENFXZ&location=` + latitude + ',' + longitude,
        //             success: res => {
        //                 let address = res.data.result.address_component
        //                 let city = address.city
        //                 let area = address.district
        //                 that.setData({
        //                     [`user[${params.idx}].value`]: city + '-' + area
        //                 })
        //             }
        //         })
        //     }
        // })

        wx.hideLoading()

    },
    xSubmit: function () {
        let that = this
        let user = that.data.user
        // 校验是否必填
        // for (var i in user) {
        //   if (user[i].value === '' ) {
        //       wx.showModal({
        //           title: user[i].cn + '未填写',
        //           cancelColor: '#9a9a9a',
        //           confirmColor: '#BC91F2',
        //           confirmText: '确定',
        //           success: res => {
        //               if (res.confirm) {
                          
        //               }
        //           }
        //       })
        //       return 
        //   }
        // }
        wx.showLoading({
          title: '保存中',
        })
        that.xUpload(user)
    },
    xUpload: function (data) {
        let form = {}
        let that =this;
        for (var i = 0; i < data.length; i++) {
            if (data[i].value !== '') {
                form[data[i].key] = data[i].value
            }
        }
        wx.cloud.callFunction({
            name: "user",
            data: {
                action: "edit",
                formdata: form
            }
        }).then(res => {
            wx.showToast({
                title: '保存成功',
                icon: 'none',
                success: () => {
                    setTimeout(() => {
                        that.xChildReload()
                        wx.navigateBack({
                            delta: 1,
                        })
                    }, 1000)
                }
            })
        })
    }
})